package com.sojson.util.id;

import java.security.SecureRandom;

import com.sojson.util.DateUtil;
import com.sojson.util.encryption.EncryptionUtil;

/**
 * 编号工具类
 *
 * @author lzlg
 * 2020/11/26 15:59
 */
public class NoUtil {

    private NoUtil() {}

    // 编号头
    private static final String HEAD = "1";
    // 机房编号(3位)
    private static final String MACHINE_ROOM = "001";
    // 机器编号(4位)
    private static final String MACHINE = "0001";
    // 4位随机字符
    private static final String PROJECT = MACHINE_ROOM + MACHINE;
    // 随机数对象
    private static final SecureRandom RANDOM = new SecureRandom();
    // 4位随机字符
    private static final String RANDOM_CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    /**
     * 邀请码编号,格式ID+YQM20201126161000ABCD
     */
    public static String yqm(int id) {
        return no(id + "YQM");
    }

    /**
     * 协议编号,格式XY20201126161000ABCD
     */
    public static String mean() {
        return no("XY");
    }

    /**
     * 订单编号,格式XY20201126161000ABCD
     */
    public static String order() {
        return no("DD");
    }

    /**
     * 助力码,格式活动编号,当前用户编号
     */
    public static String helpCodeNo(String activityNo, String userNo) {
        return encryptionReversible(activityNo + "," + userNo);
    }

    /**
     * 解密助力码,格式活动ID,当前用户ID
     */
    public static String parseHelpCodeNo(String helpCode) {
        return decryption(helpCode);
    }

    public static String no() {
        return HEAD + nowString() + PROJECT + new String(chars(4, RANDOM_CHAR));
    }

    private static String no(String key) {
        return key + nowString() + PROJECT + new String(chars(4, RANDOM_CHAR));
    }

    /**
     * 随机码
     */
    private static char[] chars(int n, String base) {
        char[] chars = new char[n];
        for (int index = 0; index < chars.length; ++index) {
            chars[index] = base.charAt(RANDOM.nextInt(base.length()));
        }
        return chars;
    }

    /**
     * 解密方法
     * 
     * @param inStr
     * @return
     */
    private static String nowString() {
        return DateUtil.nowString(DateUtil.YYYYMMDDHHMMSS);
    }

    /**
     * 解密方法
     * 
     * @param inStr
     * @return
     */
    private static String decryption(String inStr) {
        return EncryptionUtil.decryption(inStr);
    }

    /**
     * 可逆的加密方法
     * 
     * @param inStr
     * @return
     */
    private static String encryptionReversible(String inStr) {
        return EncryptionUtil.encryptionReversible(inStr);
    }

}